<?php

namespace App\Http\Controllers;

use App\Modules\User\Token;
use App\Services\Manage\ManageIndex;
use App\Services\User\UserIndex;
use Illuminate\Http\Request;

class AdapterApiController extends Controller
{

    // 允许此域名发起的跨域请求
    private $arrow = [
        'null',
        'http://localhost:8080',
        'http://newthink.local',
        'http://www.newthink.local',
    ];

    /**
     * @var array API返回格式
     */
    private $apiReturnForm = [
        'status'    => 0,
        'code'      => 0,
        'msg'       => '',
        'res'       => [],
        'token'     => ''
    ];

    /**
     * api 用户初次登录 获取token
     */
    public function getToken(Request $request)
    {
        $this->_echoHeader($request);
        $psotData = (array) json_decode($request->input('textData', ''), TRUE);
        $psotData['token']  = $request->input('token', null);
        $token = app()->make(Token::class)->setPostData($psotData)->getToken();

        # 适配app端深嵌套
        if (SUCCESS_STATUS === $token['status'])
            return response()->json(auto_success([$token]));
        else
            return response()->json(auto_failure([$token]));
//        return response()->json($token);
    }

    /**
     * 请求入口
     * @param Request $request
     * @return string
     * @throws \App\Exceptions\RequestFailException
     */
    public function index(Request $request) {
        $this->_echoHeader($request);

        # 解析请求
        list($module, $action) = $this->resolveActMap($request->only(['ver', 'module', 'controller']), $request->action);

        # 权限验证
        $token = $request->input('token', null);
        $authCheck = UserIndex::Token()->checkAuths($token, $module . '@' . $action);
        if (SUCCESS_STATUS !== $authCheck['status']) {
            //检测用户是否登录
            $checkRes = (new \App\Services\User\Token)->hGetAll($token);
            if(!isset($checkRes['res']['id']))
                return need_login(null, '请登录');
            return response()->json($authCheck);
        }

        # 执行操作
        $psotData = (array) json_decode($request->input('textData', ''), TRUE);
        $psotData['token']  = $token;
        $psotData['create_ip']  = $request->getClientIp();
        $res = app()->make($module)->setPostData($psotData)->$action();

        # api 返回
        return response()->json($res);
    }

    /**
     * 解析API 请求映射
     *
     * 根据TP5项目中路径 获取新项目的应用层控制器 和方法
     * @param $classParams
     * @param $method
     * @return array
     * @throws \App\Exceptions\RequestFailException
     */
    private function resolveActMap($classParams, $method)
    {
        $classPath = implode('/', $classParams) ;
        $toPath = config('prorequest.map.' . $classPath . '@' . $method, null);
        # 解析方法到方法的配置
        if ($toPath) {
            return explode('@', $toPath);
        }
        # 解析类到类的配置
        $toPath = config('prorequest.map.' . $classPath, null);
        if ($toPath) {
            return [$toPath, $method];
        }

        #
        throw_exception('解析应用层失败');
    }

    /**
     * 输出跨域的头
     * @param $request
     */
    private function _echoHeader($request){
        $httpOrigin = $request->server('HTTP_ORIGIN');

        if (env('APP_DEBUG')) {
            header('Access-Control-Allow-Origin: ' . $httpOrigin);
            header('Access-Control-Allow-Credentials: true');
        } elseif (in_array($httpOrigin, $this->arrow)){
            header('Access-Control-Allow-Origin: ' . $httpOrigin);
            header('Access-Control-Allow-Credentials: true');
        }
    }

    /**
     * @param Request $request
     * @return array
     */
    public function rewriteapi(Request $request): array
    {
        $this->_echoHeader($request);

        $data = $request->all();
        // 获取分类树
        $res = ManageIndex::Api()->rewriteapi($data);
        return auto_return($res, '修改重写标识成功', '修改重写标识失败');
    }
    /**
     * 获取当前的app分类树
     * @param Request $request
     * @return array
     */
    public function getcate(Request $request): array
    {
        $this->_echoHeader($request);
        // 获取分类树
        $tree = ManageIndex::ApiCate()->getCateTree($request->input('table', ''));
        return auto_return($tree, '找到分类树', '没有数据');
    }

    /**
     * 获取总接口数量及各状态数量
     * @param Request $request
     * @return array
     */
    public function getcount(Request $request): array
    {
        $this->_echoHeader($request);

        $res = ManageIndex::Api()->getCountData($request->input('table', ''));
        return auto_return($res, '找到统计数据', '没有数据');
    }
    // 获取该分类下的所有可用api
    public function cateApis(Request $request): array
    {
        $this->_echoHeader($request);

        $id = $request->query('id');
        $data['api_cate_id'] = $id;

        $res = ManageIndex::Api()->getCateApis($data, $request->input('table', ''));
        return auto_return($res, '找到接口列表', '没有数据');
    }
//
//    // 获取允计创建的版本
//    public function getArrowVer(): array
//    {
//        $this->_echoHeader();
//        $res = config('arrow_make_server');
//        return auto_return($res);
//    }
//    // 创建api分类
//    public function createApiCate(): array
//    {
//        $this->_echoHeader();
//        if (!EDIT_API) {
//            return verify_err([], '接口不可编辑!');
//        }
//        $data['name'] = input('post.name');
//        $data['glyphicons'] = input('post.glyphicons');
//        $data['parent_id'] = input('post.parent_id');
//        $data['level'] = input('post.level');
//        $data['action'] = input('post.action');
//        $data['ver'] = input('post.ver');
//        $data['status'] = input('post.status') === 'true' ? '1' : '0';
//        $data['order'] = input('post.order');
//        $validate = validate('ApiCate');
//        if(!$validate->check($data)){
//            return verify_err($data, $validate->getError());
//        }
//        $res = logic('ApiCate')->addCate($data);
//        return auto_return($res);
//    }
//    // 禁用一个api分类
//    public function removeCate (): array
//    {
//        $this->_echoHeader();
//        if (!EDIT_API) {
//            return verify_err([], '接口不可编辑!');
//        }
//        $data['id'] = input('post.id');
//        $validate = validate('ApiCate');
//        if(!$validate->check($data)){
//            return verify_err($data, $validate->getError());
//        }
//        $res = logic('ApiCate')->removeCate($data);
//
//        return auto_return($res);
//    }
    // 增加api接口
    public function addApi (Request $request): array
    {
        $this->_echoHeader($request);
        if (!EDIT_API) {
            return verify_err([], '接口不可编辑!');
        }
        $data = $request->all();
        $res = ManageIndex::Api()->addApi($data);
        return auto_return($res);
    }

    public function editApi(Request $request): array
    {
        $this->_echoHeader($request);
        $data = $request->all();
        $res = ManageIndex::Api()->editApi($data);
        return auto_return($res);
    }

    // 获取接口详情
    public function getApiDetail(Request $request): array
    {
        $this->_echoHeader($request);
        if (!EDIT_API) {
            return verify_err([], '接口不可编辑!');
        }
        $data = $request->all();
        $res = ManageIndex::Api()->getApiDetail($data);
        return auto_return($res);
    }

//    // 删除一个接口
//    public function removeApi (): array
//    {
//        $this->_echoHeader();
//        if (!EDIT_API) {
//            return verify_err([], '接口不可编辑!');
//        }
//        $data['id'] = input('get.id');
//        $validate = validate('Api');
//        if(!$validate->check($data)){
//            return verify_err($data, $validate->getError());
//        }
//        $res = logic('Api')->removeApi($data);
//        return auto_return($res);
//    }
//
    public function upload(Request $request)
    {
       $this->_echoHeader($request);
       $file = new \App\Services\File\File();
       return $file->upload($request);
    }
}
